<?php
	include('adodb/adodb.inc.php');
	$user = "rrikal_db";
	$pwd = "manukali";
	$db = "rrikal_db";
	$server = "mysql4.freehostia.com";
    //$server = 'localhost';
    $table_prefix = "mm_";

    /////////////////////////////////////////////// DB connect ////////////////////////////////////////////////
    $DB = NewADOConnection('mysql');
    $DB->Connect($server, $user, $pwd, $db);
    $DB->SetFetchMode(ADODB_FETCH_ASSOC);
    ///////////////////////////////////////////////////////////////////////////////////////////////////


	$Months = array( 1=>"January","February","March","April","May","June","July","August","September","October","November","December");

    function checkUserphp($name)
    {
    global $DB, $table_prefix;
    $result=$DB->GetOne("select user_id from ${table_prefix}user where user_name=?",array($name));

    if($result== NULL)
        return false;
    else
        return true;

   }


    function getCategory()
    {
    global $DB, $table_prefix;
    $rs = $DB->GetAll("select * from ${table_prefix}category");

    if (!$rs)
    	print $DB->ErrorMsg();
       return $rs;
    }
    //////////////////////////////////////////////// get Question ////////////////////////////////////////////
    function getQuestion()
    {
    global $DB, $table_prefix;
    $rs = $DB->GetAll("select que_id, ques_des from ${table_prefix}question");

    if (!$rs)
    	print $DB->ErrorMsg();

    return $rs;
    }

    function addUser($name,$pass,$qid,$ans)
    {
     global $DB, $table_prefix;
     $record = array();
     $record["user_name"] = $name;
     $record["user_pass"] = md5($pass);
     $record["secret_qid"] = $qid;
     $record["secret_ans"] = $ans;

     $rs =& $DB->AutoExecute("`${table_prefix}user`", $record, 'INSERT');

     if (!$rs)
        echo ($DB->ErrorMsg());

	 $arr1 = $DB->GetOne("select user_id from ${table_prefix}user where user_name = ?",array($name));

	 $ccrec = array();
	 $ccrec["cc_nickname"]= "Cash";
	 $ccrec["user_id"]= $arr1;

	 $crs =& $DB->AutoExecute("`${table_prefix}cctable`", $ccrec, 'INSERT');

	 }


    /////////////////////////////////////////////// Get Categories //////////////////////////////////////////
    function addExpense($amt,$date,$desc,$cate, $userid,$trantype)
    {
     global $DB, $table_prefix;
     $record = array();
     $record["category_id"] = (int)$cate;
     $record["exp_date"] = $date;
     $record["exp_desc"] = $desc;
     $record["exp_amt"] = $amt;
     $record["user_id"] = $userid;
     $record["cc_id"] = $trantype;
     $rs =& $DB->AutoExecute("`${table_prefix}expense`", $record, 'INSERT');

     if (!$rs)
        echo ($DB->ErrorMsg());

    }

    /////////////////////////////////////////////// Insert Expense/////////////////////////////////////////

    function getAlldata()
    {
     global $DB, $table_prefix;
     $arr = $DB->GetAll("select * from ${table_prefix}expense e, ${table_prefix}category c, ${table_prefix}cctable cc where e.category_id=c.category_id and e.cc_id=cc.cc_id order by exp_date desc");

	 if (!$arr)
     echo ($DB->ErrorMsg());

     return $arr;
     }

     /////////////////////////////////////////////Display expenses///////////////////////////////////////
    function getYeardata($y = false, $user, $cat = false)
    {
       	global $DB, $table_prefix;
	if(empty($y)) {
	    $y = date('Y');
	}
	$query = "select sum(exp_amt) from ${table_prefix}expense where user_id = ? and exp_date like ?";
	if(!empty($cat)) {
	    $query .= " and category_id = " . $cat;
	}
	$arr = $DB->GetOne($query, array($user, $y . '-%'));
	if(!$arr)
	    echo($DB->ErrorMsg());
	return $arr;
    }

    /////////////////////////////////////////////Display expenses///////////////////////////////////////
    function getMonthdata($m,$d,$y)
    {
    global $DB, $table_prefix;
    $today = $y."-".$m."-01";

    $dt =& new Date($today);
    $numdays = $dt->getDaysInMonth();
    $endmonth = $y."-".$m."-".$numdays;

    $arr = $DB->GetOne("select sum(exp_amt) from ${table_prefix}expense where user_id = ? and exp_date >= ? and exp_date <=?",array($_SESSION["userid"],$today,$endmonth));
    if(!$arr)
    echo($DB->ErrorMsg());

    return $arr;
    }
	///////////////////////////////////////////////////Get week's expense///////////////////////////////////////

    function getWeekdata($m,$d,$y, $user, $cat=false)
    {
    global $DB, $table_prefix;
    $year = $y;
    $month = $m;    ;
    $dayofmonth = $d; // returns today's date

    $passdate = $y."-".sprintf("%02d",$m)."-".sprintf("%02d",$d);

    $passdt =& new Date($passdate);
    $dayofweek = $passdt->getDayOfWeek();

    $date_diff = 6 - $dayofweek - 1;
    $nextday = $passdt->getNextDay();
	$prevday = $passdt->getPrevDay();

	for($i=0;$i<$date_diff;$i++)
    {
       $nextday = $nextday->getNextDay();
       $s_date = $nextday->getDay();
       $s_month = $nextday->getMonth();
       $s_year = $nextday->getYear();
    }

    $saturday = $s_year."-".sprintf("%02d",$s_month)."-".sprintf("%02d",$s_date);

	for($i=$dayofweek;$i>=0;$i--)
	{
		$prevday = $prevday->getPrevDay();
		$p_date = $prevday->getDay();
		$p_month = $prevday->getMonth();
		$p_year = $prevday->getYear();
	}

    $sunday = $p_year."-".sprintf("%02d",$p_month)."-".sprintf("%02d",$p_date);


    $query = "select sum(exp_amt) from ${table_prefix}expense where user_id = ? and exp_date >= ? and exp_date <= ?";
    if(!empty($cat)) {
        $query .= " and category_id = " . $cat;
    }
    $arr = $DB->GetOne($query, array($user,$sunday,$saturday));

    if($arr == NULL)
        $arr = FALSE;

     return $arr;

    }

//////////////////////////////////////////////// function for calender ////////////////////////////////////

    function getSunday($dayofw,$m,$y)
    {
    global $DB, $table_prefix;
    $year = $y;
    $month = $m;
    $dayofmonth = 1;
    $dayofweek = $dayofw;

    if( ($dayofmonth >= 1) and ($dayofmonth <= 6))
    {

          if ($dayofmonth == 1)
           {
           // setting up month and year
                if ($month == 1)
                 {
                    $year = $year - 1;
                    $month = 12;
                 }
                else
                 {
                $month = $month - 1;
                 }
          // setting up month and year

                $dayofmonth = daysInMonth($month);

           }

      $dayofmonth = $dayofmonth + 1 - $dayofweek;

      if($dayofmonth < 0)
      {
        $dayofmonth = $dayofmonth - 1;
        $prevmonth = $month -1 ;

        $prevmdays = daysInMonth($prevmonth);
        $dayofmonth = $dayofmonth + $prevmdays;
        $sunday = $year."-".$prevmonth."-".$dayofmonth;
      }
    }
    else
    {
    $dayofmonth = $dayofmonth - $dayofweek;
    $sunday = $year."-".$month."-".$dayofmonth;
    }
    return $dayofmonth;
    }
///////////////////////////////////////////// days in a month    //////////////////////////////
   function daysInMonth($month)
    {
       if($month == 2)
       {
          //  check if year is leap
             if( ($year % 4 == 0 && ($year % 400 == 0 || $year % 100 != 0) == true))
                $numberdays = 29;
              else
                $numberdays = 28;
       }
           if(($month==1) || ($month==3) || ($month==5) || ($month==7) || ($month==8) || ($month==10) ||  ($month==12) )
             $numberdays = 31;
       else
           if($month !=2)
              {
              $numberdays = 30;
              }

        return $numberdays;

    }
    //////////////////////////////////////////////// end ////////////////////////////////////

    function getExpforDate($year,$month,$day, $userid)
    {
     global $DB, $table_prefix;
     $today = $year."-".$month."-".$day;
     $arr = $DB->GetAll("select * from ${table_prefix}expense e, ${table_prefix}category c, ${table_prefix}cctable cc where e.category_id=c.category_id  and e.cc_id=cc.cc_id and e.user_id = ? and exp_date = ?", array($userid, $today));

     if (!$arr)
     echo ($DB->ErrorMsg());

     return $arr;
     }

    function getsumExpforDate($year,$month,$day)
    {
     global $DB, $table_prefix;
     $today = $year."-".$month."-".$day;
     $arr = $DB->GetOne("select sum(exp_amt) from ${table_prefix}expense where user_id = ? and exp_date = ?", array($_SESSION["userid"], $today));
     if (!$arr)
     echo ($DB->ErrorMsg());

     return $arr;
    }

    function getCategoryExpenseForMonth($year, $month, $cat, $user) {
	    global $DB, $table_prefix;
	$catexp = $DB->GetOne("select sum(exp_amt) from ${table_prefix}expense where category_id = ? and user_id = ? and exp_date like '" . $year ."-". $month . "-%'", array($cat, $user));
	if(!$catexp) {
		print $DB->ErrorMsg();
		return false;
	}
	return $catexp;
    }

    function getTotalExpenseForMonth($year, $month, $user) {
	global $DB, $table_prefix;
	$catexp = $DB->GetOne("select sum(exp_amt) from ${table_prefix}expense where user_id = ? and exp_date like '" . $year . "-".$month . "-%'", array($user));
	if(!$catexp) {
		print $DB->ErrorMsg();
		return false;
	}
	return $catexp;
    }

    ////////////////////////////////////////////
    function addCredit($nickname,$userid)
	    {
	     global $DB, $table_prefix;
	     $record = array();
	     $record["cc_nickname"] = $nickname;
	     $record["user_id"] = $userid;
	     $rs =& $DB->AutoExecute("`${table_prefix}cctable`", $record, 'INSERT');
		 if (!$rs)
	        echo ($DB->ErrorMsg());

	    }

    function saveCreditCard($id, $name, $userid) {
	    global $DB, $table_prefix;
	    $cc = $DB->GetRow("select * from ${table_prefix}cctable where "
		    . "cc_id = ? and user_id = ?", array($id, $userid));
	    if(!$cc || empty($cc)) {
		print $DB->ErrorMsg();
		return FALSE;
	    }
	    $cc['cc_nickname'] = $name;
	    $DB->AutoExecute("`${table_prefix}cctable`", $cc, 'UPDATE', "cc_id = " . $id . " and user_id = " . $userid);
    }

    function checkDup($nickname,$user)
    {
    	global $DB, $table_prefix;

    	$arr = $DB->GetOne("select cc_nickname from ${table_prefix}cctable where user_id =?  and cc_nickname =?", array($user,$nickname));

		if (!$arr)
			return false;
		else
			return true;
    }

    function getCreditCard($id, $user) {
	    global $DB, $table_prefix;
	    $cc = $DB->GetRow("select * from ${table_prefix}cctable where "
		    . "cc_id = ? and user_id = ?", array($id, $user));
	    if(!$crs) {
		    print $DB->ErrorMsg();
	    }
	    return $cc;
    }

    function deleteCreditCard($id, $user) {
	    global $DB, $table_prefix;
	    $rs = $DB->Execute("DELETE FROM ${table_prefix}cctable where "
		    . "cc_id = ? and user_id = ?", array($id, $user));
	    if(!$rs) {
		    print $DB->ErrorMsg();
		    return FALSE;
	    }
	    return TRUE;
    }

    function getCreditCards($user)
    {
    global $DB, $table_prefix;
    $crs = $DB->GetAll("select cc_nickname,cc_id from ${table_prefix}cctable where user_id=?",array($user));

    if (!$crs)
    	print $DB->ErrorMsg();
    return $crs;
    }

	function getCreditCardsncash($user)
    {
    global $DB, $table_prefix;
    $crs = $DB->GetAll("select cc_nickname,cc_id from ${table_prefix}cctable where cc_nickname not in ('Cash') and user_id=? order by cc_nickname",array($user));

    if (!$crs)
    	print $DB->ErrorMsg();
    return $crs;
    }


    function delExpense($expid,$user)
    {
    global $DB, $table_prefix;
    $result= $DB->Execute("Delete from ${table_prefix}expense where exp_id=? and user_id=?",array($expid,$user));

	if (!$result)
	    	print $DB->ErrorMsg();

    }

	function getExpDetails($expid,$user)
	{
	global $DB, $table_prefix;
	$expdetails=$DB->GetRow("select * from ${table_prefix}expense where exp_id=? and user_id=?",array($expid,$user));

	if (!$expdetails)
	    	print $DB->ErrorMsg();

	return $expdetails;
	}

	function UpdateExpense($exppass,$amt,$date,$desc,$cate, $userid,$trantype)
    {
		 global $DB, $table_prefix;
		 $record = array();
		 $record["exp_id"] = $exppass;
		 $record["category_id"] = (int)$cate;
		 $record["exp_date"] = $date;
		 $record["exp_desc"] = $desc;
		 $record["exp_amt"] = $amt;
		 $record["user_id"] = $userid;
		 $record["cc_id"] = $trantype;
		 $rs =& $DB->AutoExecute("`${table_prefix}expense`", $record, 'UPDATE', "exp_id = " . $exppass);

		 if (!$rs)
			echo ($DB->ErrorMsg());

    }
?>
